package router

import (
	"bluebell/controller"
	"bluebell/pkg/jwt"
	"github.com/gin-gonic/gin"
	"github.com/juju/ratelimit"
	"net/http"
	"strings"
	"time"
)

func JWTMiddleware() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		authHeader := ctx.Request.Header.Get("Authorization")
		if authHeader == "" {
			controller.ResponseError(ctx, 403, "请登录")
			ctx.Abort()
			return
		}
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			controller.ResponseError(ctx, 403, "token有误")
			ctx.Abort()
			return
		}
		mc, err := jwt.ParseToken(parts[1])
		if err != nil {
			controller.ResponseError(ctx, 403, "token无效")
			ctx.Abort()
			return
		}
		ctx.Set("userID", mc.UserID) // 将请求的username信息保存到请求的ctx上
		ctx.Next()                   // 后续处理函数可以通过ctx.Get("username")来获取当前请求的用户信息
	}
}

func ReteLimitMiddleware(fillInterval time.Duration, cap int64) func(ctx *gin.Context) {
	bucket := ratelimit.NewBucket(fillInterval, cap)
	return func(ctx *gin.Context) {
		// 如果取不到令牌就返回响应(bucket.Take(1)表示获取1个令牌需要等待的时间)
		if bucket.TakeAvailable(1) == 0 { // 0表示取不到足够的令牌
			ctx.String(http.StatusOK, "rate limit...")
			ctx.Abort()
			return
		}
		// 取到令牌就放行
		ctx.Next()
	}
}
